package org.luxor.commons.jdbc.plugin.dynamic.processor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.luxor.commons.core.utils.StringUtils;
import org.springframework.core.env.Environment;
import org.springframework.lang.Nullable;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Mr.yan
 * @dae 2020/3/21
 */
public class DsValueProcessor extends DsProcessor {
    private static final String VALUE_EL_REGEX = "\\$\\{[\\.|\\w|\\:]*\\}";
    private static final Pattern VALUE_PATTERN = Pattern.compile("(?<=\\$\\{)(\\S+)(?=\\})");
    private static final String DEFAULT_VALUE_SEPARATOR = ":";

    @Nullable
    private Environment environment;

    public DsValueProcessor(Environment environment) {
        this.environment = environment;
    }

    @Override
    public boolean matches(String key) {
        return key != null && Pattern.matches(VALUE_EL_REGEX, key);
    }

    @Override
    public String doDetermineDatasource(ProceedingJoinPoint pjp, String value) {
        String key = null;
        String defaultKey = null;

        Matcher mat = VALUE_PATTERN.matcher(value);
        while (mat.find()) {
            key = mat.group();
        }

        if (StringUtils.contains(key, DEFAULT_VALUE_SEPARATOR)) {
            int index = key.indexOf(DEFAULT_VALUE_SEPARATOR);
            defaultKey = key.substring(index + 1);

            key = key.substring(0, index);
        }
        return environment.getProperty(key, defaultKey);
    }
}
